package service;

import java.util.ArrayList;

import server.AuctionServerThread;

import domain.Auction;

public class AuctionHolder {

	private static ArrayList<Auction> activeAuctions;
	private static final Object singletonObject = new Object();
	private static AuctionHolder instance;

	private AuctionHolder() {
		activeAuctions = new ArrayList<Auction>();
	}

	
	 

	public static AuctionHolder getInstance() {
		if(instance == null) {
			synchronized(singletonObject) {
				if(instance==null) instance = new AuctionHolder();
			}
		}
		
		return instance;
	}

	public void removeAuction(Auction auction) {
		synchronized(this) {
			activeAuctions.remove(auction);
		}
	}

	public String getAuctionList() {
		String auctionList = "";

		synchronized(this) {
			for(int i=0;i<activeAuctions.size();i++) {
				if(i<activeAuctions.size()-1) auctionList+=activeAuctions.get(i).toString()+"\n";
				else auctionList+=activeAuctions.get(i).toString();
			}
		}

		if(auctionList.equals("")) auctionList = "No auctions running.";

		return auctionList+"\n*endlist*";
	}

	public void add(Auction auction) {
		synchronized(this) {
			activeAuctions.add(auction);
		}
	}
	
	/**
	 * @return the activeAuctions
	 */
	public static ArrayList<Auction> getActiveAuctions() {
		return activeAuctions;
	}




	public Auction highestBid(int id){
		Auction result = null;
		synchronized (this) {
			for (int i = 0; i < activeAuctions.size(); i++) {
				if(id==activeAuctions.get(i).getId()){
					result = activeAuctions.get(i);
				}
			}
		}
		return result;
	}


	public Auction bid(int id, double bid, String username, AuctionServerThread thread) {
		
		Auction result = null;
		
		synchronized(this) {
			for(int i=0;i<activeAuctions.size();i++){
				if(id==activeAuctions.get(i).getId()) {
					
					if(bid>activeAuctions.get(i).getBid()) {
						thread.setOldBidder(activeAuctions.get(i).getBidder());
						activeAuctions.get(i).setBid(bid);
						activeAuctions.get(i).setBidder(username);
					}
					
					result = activeAuctions.get(i);
					break;
				}
			}
		}
		
		
		return result;
	}

	public boolean checkAuctionId(int id) {
		boolean check = false;
		
		for (int i = 0; i < activeAuctions.size(); i++) {
			if(activeAuctions.get(i).getId() == id){
				check = true;
			}
		}
		
		return check;
	}


}
